var _NORMAL = "0000000";

/**
 * 重置表格数据
 */
function loadPqGridData($grid, gridData) {
    if ($grid.length > 0) {
        function updateToolBar($grid, total) {
            var realTotal, toolbar;
            if (total) {
                realTotal = total;
            } else {
                realTotal = _pqUtil.f.getTotalCount($grid);
            }
            toolbar = $grid.pqGrid("option", "toolbar");
            toolbar.items[1].type = "<span>共 " + realTotal + " 条</span>";
            $grid.pqGrid("refreshToolbar");
        }
        _pqUtil.f.cleanAndResetGrid($grid);
        $grid.pqGrid('option', 'dataModel.data', gridData);
        $grid.pqGrid("refreshDataAndView");
        updateToolBar($grid, gridData.length);
    }
}

/**
 * 获取表格数据
 */
function getGridData() {
    var dataCate = $.trim($("#dataCateSel").val());
    var order_by_column;
    if ('EFGR' === dataCate){
        order_by_column = 'dataId,ext1,ext2';
    }else if ('ETTA' === dataCate){
        order_by_column = 'dataId,ext3,ext1,ext2';
    }else if ('LIAT' === dataCate){
        order_by_column = 'ext1,dataId';
    }
    var iary = [{
        data_cate       : dataCate
    }];
    var inTrxObj = {
        trx_id          : 'XPBASICDATA',
        action_flg      : 'Q',
        order_by_column : order_by_column,
        iary            : iary
    };
    var outTrxObj = comTrxSubSendPostJson(inTrxObj);
    if( outTrxObj.rtn_code == _NORMAL ) {
        loadPqGridData($("#dataListGrd"), outTrxObj.oary);
    }
}

/**
 * 导入Excel文件
 */
function initUpload() {
    var datas = {
        codeCate : $("#dataCateSel").val(),
        user     :$("#userSpan").text()
    };
    $('#fileinput').fileupload({
        dataType: 'json',
        limitMultiFileUploads: 1,
        add: function (e, data) {
            $('#versionId').val(data.files[0].name);
            $('#process').empty();
            $("#uploadBisDataBtn").unbind("click").bind('click', function () {
                $('#process').empty();
                var codeCate = $("#dataCateSel").val();
                var userId = $("#userSpan").text();
                datas = {
                    codeCate: codeCate,
                    user:userId
                };
                data.formData = datas;
                data.submit();
                $("#uploadBisDataModel").modal("hide");
                $("#download_btn").attr("disabled",true);
            });
        },
        done: function (e, data) {
            if (data.result.rtn_mesg == 'success') {
                $('#process').empty();
                showSuccessDialog("导入成功");
            } else {
                $('#process').empty();
                $('#versionId').val();
                showSuccessDialog(data.result.rtn_mesg);
            }
            $('#download_btn').removeAttr('disabled');
            getGridData();
        },
        fail: function (e, data) {
            $('#process').empty();
            $('#versionId').val();
            $('#download_btn').removeAttr('disabled');
            showErrorDialog("解析失败","请检查文档内容格式!");
        }
    });
}

/**
 * 获取参数列设定
 */
function getColumnDesc() {
    var colM = [];
    // colM.push({dataIndx: "state",align: "center", title: "<input type='checkbox' />", cb: { header: true, select: true, all: true }, type: 'checkbox', dataType: 'bool', editor: false, exportRender: false });
    colM.push({title: "删除", align:'center', editable: false, minWidth: 60, sortable: false,
            render: function (ui) {
                return "<button type='button' class='del_btn'>删除</button>";
            },
            postRender: function (ui) {
                var rowIndx = ui.rowIndx,
                    grid = this,
                    $cell = grid.getCell(ui);
                $cell.find(".del_btn").button({icons: {primary: 'ui-icon-pencil'}}).bind("click", function (evt) {
                    var rowData = ui.rowData;
                    $(this).showCallBackWarnningDialog({
                        errMsg  : "是否删除参数,请确认!!!!",
                        callbackFn: function (data) {
                            if (data.result == true) {
                                var iary = {
                                    data_seq_id : rowData.dataSeqId,
                                    evt_usr     : $("#userSpan").text()
                                };
                                var inTrxObj = {
                                    trx_id     : 'XPBASICDATA',
                                    action_flg : 'D',
                                    iary       : [iary]
                                };
                                var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
                                if(  outTrxObj.rtn_code == _NORMAL ) {
                                    getGridData();
                                    showSuccessDialog("删除数据成功");
                                }
                            }
                        }
                    });
                        return false; //屏蔽其他事件
                    });
            }
    });
    colM.push({halign:'center', align:'center',  dataIndx: "dataSeqId", title: "dataSeqId", width: 250, editable: false, sortable: true, hidden: true});
    var iary = [{
        data_cate : "CODE",
        data_id   : $.trim($("#dataCateSel").val())
    }];
    var inTrxObj = {
        trx_id     : 'XPBASICDATA',
        action_flg : "Q"        ,
        iary       : iary
    };
    var  outTrxObj = comTrxSubSendPostJson(inTrxObj);
    if( outTrxObj.rtn_code == _NORMAL ) {
        var tbl_cnt = outTrxObj.tbl_cnt;
        for (var i = 0; i < tbl_cnt; i++) {
            var oary = outTrxObj.oary[i];
            switch (oary.dataExt.trim()) {
                case "DATA_ID":
                    colM.push({halign:'center', align:'center',  dataIndx: "dataId", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
                case "DATA_EXT":
                    colM.push({halign:'center', align:'center',  dataIndx: "dataExt", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
                case "DATA_ITEM":
                    colM.push({halign:'center', align:'center',  dataIndx: "dataItem", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
                case "DATA_DESC":
                    colM.push({halign:'center', align:'center',  dataIndx: "dataDesc", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
                case "EXT_1":
                    colM.push({halign:'center', align:'center',  dataIndx: "ext1", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
                case "EXT_2":
                    colM.push({halign:'center', align:'center',  dataIndx: "ext2", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
                case "EXT_3":
                    colM.push({halign:'center', align:'center',  dataIndx: "ext3", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
                case "EXT_4":
                    colM.push({halign:'center', align:'center',  dataIndx: "ext4", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
                case "EXT_5":
                    colM.push({halign:'center', align:'center',  dataIndx: "ext5", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
                case "EXT_6":
                    colM.push({halign:'center', align:'center',  dataIndx: "ext6", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
                case "EXT_7":
                    colM.push({halign:'center', align:'center',  dataIndx: "ext7", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
                case "EXT_8":
                    colM.push({halign:'center', align:'center',  dataIndx: "ext8", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
                case "EXT_9":
                    colM.push({halign:'center', align:'center',  dataIndx: "ext9", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
                case "EXT_10":
                    colM.push({halign:'center', align:'center',  dataIndx: "ext10", title: oary.dataDesc.trim(), width: 250, editable: true, sortable: true});
                    break;
            }
        }
        $( "#dataListGrd" ).pqGrid( "option", "colModel", colM );
        $( "#dataListGrd" ).pqGrid( "refreshView" );
    }
}

/**
 * 初始化事件
 */
function initEvents() {
    /**
     * 修改数据
     */
    $("#dataListGrd").pqGrid({
        cellSave: function( event, ui ) {
            if (ui.newVal !== ui.oldVal){
                var iary = {
                    dataSeqId : ui.rowData.dataSeqId,
                    evtUser   : $.trim($("#userSpan").text())
                };
                iary[ui.dataIndx] = ui.newVal;
                var inTrxObj = {
                    trx_id: 'XPBASICDATA',
                    action_flg: 'U',
                    iary: [iary],
                };
                var outTrxObj = comTrxSubSendPostJson(inTrxObj);
                if (outTrxObj.rtn_code == _NORMAL) {
                    showSuccessDialog("修改参数成功");
                }
            }
        }
    });

    /**
     * 新增数据
     */
    // $("#add_btn").click(function (){
    //     showBisDataDialog({
    //         action_flg       : "A",
    //         data_cate        : $.trim($("#dataCateSel").val()),
    //         data_cate_desc   : $("#dataCateSel").find("option:selected").text(),
    //         evt_usr          : $.trim($("#userSpan").text()),
    //         callbackFn : function(data) {
    //             if(data.result==true){
    //                 showMessengerSuccessDialog("新增参数成功", 3);
    //                 getGridData();
    //             }
    //         }
    //     })
    // });
    $("#add_btn").click(function (){
        $("#add_btn").showBisDataDialog({
            action_flg: "A",
            data_cate: $.trim($("#dataCateSel").val()),
            data_cate_desc: $("#dataCateSel").find("option:selected").text(),
            evt_usr: $.trim($("#userSpan").text()),
            callbackFn: function (data) {
                if (data.result == true) {
                    showMessengerSuccessDialog("新增参数成功", 3);
                    getGridData();
                }
            }
        });
    });

    /**
     * 删除数据
     */
    $("#del_btn").click(function (){
        $("#deleteDatacateDialog_deleteDateCateBtn").showCallBackWarnningDialog({
            errMsg  : "是否全部删除,请确认!!!!",
            callbackFn : function(data) {
                if(data.result==true){
                    var obj = this ;
                    var allRowData = $( "#dataListGrd" ).pqGrid( "getData" );
                    var iaryI = [];
                    for(var i=0;i<allRowData.length;i++){
                        var rowData = allRowData[i];
                        var iary = {
                            data_seq_id : rowData.dataSeqId,
                            evt_user : $("#userSpan").text()
                        };
                        iaryI.push(iary);
                    }
                    var inTrxObj = {
                        trx_id     : 'XPBASICDATA',
                        action_flg : 'D',
                        iary       : iaryI
                    };
                    var outTrxObj = comTrxSubSendPostJson(inTrxObj);
                    console.log("deleteDatacateDialog_deleteDateCateBtn:     "+outTrxObj);
                    if(  outTrxObj.rtn_code == _NORMAL ) {
                        showSuccessDialog("删除成功");
                        getGridData();
                    }
                }
            }
        });
    });

    /**
     * 参数类型Change事件
     */
    $("#dataCateSel").change(function () {
        getColumnDesc();
        getGridData();
    });

    /**
     * 下载Excel模板
     */
    $("#download_btn").click(function (){
        //if ($("#downForm").length > 0) {
        //    $("#downForm").remove();
        //}
        //var str = '<form id="downForm" action="download.do" method="post">';
        //str = str + '<input type="hidden" name="fileName" id= "fileName" />';
        //str = str + "</form>";
        //$(str).appendTo("body");
        //$("#fileName").val("报表基础数据维护_" + $("#dataCateSel").text() + ".xlsx");
        //$("#downForm").submit();
        var dataCateValue = $("#dataCateSel").val();

        generateBasicDataExcel(dataCateValue, "基础参数维护_" + $("#dataCateSel").find("option:selected").text() + "_");
    });

    /**
     * 导入Excel文件按钮
     */
    $("#import_btn").click(function(){
        $("#fileinput").val("");
        $("#versionId").val("");
        $("#uploadBisDataModel").modal("show");
        if(!$("#fileinput").val()){
            $("#uploadBisDataBtn").attr("disabled",false);
        }
    });
}

/**
 * 初始化pqGrid表格
 */
function initPqGrid() {
    var colM = [];
    var data = {};
    data.grid = {
        iniDataListGrid: function () {
            var $grid = $('#dataListGrd');
            var objo = {
                width: winWidth*0.9,
                height: '700',
                postRenderInterval: -1, //synchronous post rendering.
                showTitle: false,
                title: "",
                resizable: false,
                hwrap: false,
                wrap: false,
                dragColumns: {enabled: false},
                numberCell: {
                    show: false,
                    width: 50
                },
                showBottom: false,
                showTop: true,
                showToolbar: true,
                virtualY: true,
                selectionModel: { type: 'row' },
                toolbar: {
                    items: [
                        {
                            type: 'button',
                            width: 150,
                            label: "导出Excel",
                            icon: 'ion-ios-download-outline',
                            listener: function () {
                                //var format = 'xls',
                                //    blob = this.exportData({
                                //        format: format,
                                //        render: true
                                //    });
                                //if (typeof blob === "string") {
                                //    blob = new Blob([blob]);
                                //}
                                var format = 'xlsx',
                                    blob = this.exportData({
                                        format: format,
                                        render: true,
                                        type: 'blob'
                                    });
                                var excel_name = "基础数据维护_Excel.";
                                saveAs(blob, excel_name + format);
                            }
                        },{
                            type: "<span>共 0 条</span>",
                            width: 110
                        }
                    ]
                },
                scrollModel: {
                    autoFit: false
                },
                collapsible: {
                    on: false,
                    collapsed: false,
                    toggle: false,
                },
                colModel:colM
            };
            $grid.pqGrid(objo);
        }
    };
    data.grid.iniDataListGrid();
}



$(document).ready(function() {
    initPqGrid();
    initUpload();
    getColumnDesc();
    getGridData();
    initEvents();
});
